<script setup>
import emoji from '@/utils/emoji.js'
import { ref, onMounted } from 'vue';
const emits = defineEmits(["PictureToKey"])

const emojiKey = "emojiUsed::";
// 获取本地常用表情包
const commonlyUsed = ref([]);


function imgToKey (key) {
  // 记录起来
  // 添加进常用表情
  setCommonlyUsed(key)
  emits("PictureToKey", { key, path: `src/assets/emoji/${emoji[key]}.png` })
}
onMounted(() => {
  commonlyUsed.value = localStorage.getItem(emojiKey)?.split(",") || []
})
// 添加进常用表情
function setCommonlyUsed (key) {
  // 1. 获取本地表情
  let oldData = localStorage.getItem(emojiKey)?.split(",") || [];

  // 2. 判断是否存在
  if (oldData.includes(key)) {
    // 存在 删除掉原来的 添加 
    const i = commonlyUsed.value.findIndex(item => item === key);
    commonlyUsed.value.splice(i, 1)
    oldData.splice(i, 1)
  }
  //  不存在 直接添加
  oldData.unshift(key)
  commonlyUsed.value.unshift(key)
  // 如果大于等于10
  // 进行切割
  if (oldData.length >= 10) {
    oldData.splice(10)
  }
  localStorage.setItem(emojiKey, oldData.toString());

}


</script>

<template>
  <div class="g-emoji">
    <div class="g-emoji__recent">
      <div class="g-emoji__header">最近使用</div>
      <div class="g-emoji__centent">
        <div class="g-emoji__centent__item" v-for="item in commonlyUsed" @click="imgToKey(item)">
          <img :src="`src/assets/emoji/${emoji[item]}.png`" style="height: 32px;">
        </div>

      </div>
    </div>
    <div class="g-emoji__all">
      <div class="g-emoji__header">全部表情</div>
      <div class="g-emoji__centent">
        <div v-for="item, key in emoji" class="g-emoji__centent__item" @click.stop="imgToKey(key)">
          <img :src="`src/assets/emoji/${item}.png`" style="height: 32px;">
        </div>
      </div>
    </div>
  </div>
</template>



<style lang="scss" scoped>
.g-emoji {
  padding: 16px 16px 6px;
  height: 400px;
  // background-color: white;
  left: 0;
  display: flex;
  flex-direction: column;

  &__header {
    font-size: 12px;
    color: rgb(164, 164, 164);
  }

  &__recent,
  &__all {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: center;
    gap: 10px;

  }

  &__recent {
    height: 70px;
    margin-bottom: 10px;

  }

  &__all {
    flex: 1 1 0;


  }

  &__centent {
    overflow-y: scroll;

    &::-webkit-scrollbar {
      display: none;
    }

    flex: 1 1 0;
    display: grid;
    width: 100%;
    grid-template-columns: repeat(10, 37px);
    grid-template-rows: repeat(auto-fill, minmax(40px, 1fr));
    gap: 11px;

    &__item {
      display: flex;
      justify-content: center;
      align-items: center;

      &:hover {
        background-color: #ccc;
      }

    }
  }
}
</style>